<template>
  <div class="company-bill-container">
    <!-- 公司信息 + 月份选择 -->
    <el-card class="company-info" shadow="hover">
      <div class="info-header">
        <h2>{{ company.name }} - 月度账单</h2>
        <div class="info-controls">
          <el-tag :type="tagType">{{ company.type }}</el-tag>
          <el-select v-model="selectedMonth" @change="onMonthChange" placeholder="选择月份" style="width: 150px;">
            <el-option v-for="month in availableMonths" :key="month" :label="month" :value="month" />
          </el-select>
        </div>
      </div>
      <div class="info-body">
        <p>免租期：{{ rentFreeText }}</p>
      </div>
    </el-card>

    <!-- 月账单 -->
    <el-card class="monthly-bill" shadow="hover">
      <div class="bill-header" style="display: flex; justify-content: space-between; align-items: center;">
        <h3>当前月账单（{{ selectedMonth }}）</h3>
        <el-tag :type="isPaid ? 'success' : 'danger'">{{ isPaid ? '已缴费' : '未缴费' }}</el-tag>
      </div>
      <el-descriptions border column="2" class="mb-4">
        <el-descriptions-item label="应收租金">{{ formatCurrency(currentBill.rent_due) }}</el-descriptions-item>
        <el-descriptions-item label="实收租金">{{ formatCurrency(currentBill.rent_paid) }}</el-descriptions-item>
        <el-descriptions-item label="物业费">{{ formatCurrency(currentBill.property_fee) }}</el-descriptions-item>
        <el-descriptions-item label="水电费">{{ formatCurrency(currentBill.utility_fee) }}</el-descriptions-item>
      </el-descriptions>
      <div style="text-align: right; margin-top: 10px;">
        <el-button type="primary" :disabled="isPaid" @click="payBill">缴费</el-button>
      </div>
    </el-card>

    <!-- 本月企业营收情况 -->
    <el-card class="statistics" shadow="hover">
      <h3>本月营收情况</h3>
      <el-descriptions border column="3">
        <el-descriptions-item label="总营收">{{ formatCurrency(statistics.revenue) }}</el-descriptions-item>
        <el-descriptions-item label="税收">{{ formatCurrency(statistics.tax) }}</el-descriptions-item>
        <el-descriptions-item label="利润">{{ formatCurrency(statistics.profit) }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 历史记录 -->
    <el-card class="history" shadow="hover">
      <h3>历史缴费记录</h3>
      <el-table :data="history" border stripe>
        <el-table-column prop="month" label="月份" width="100" />
        <el-table-column prop="rent_paid" label="实收租金" />
        <el-table-column prop="property_fee" label="物业费" />
        <el-table-column prop="utility_fee" label="水电费" />
        <el-table-column prop="total" label="合计" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import axios from 'axios'

const availableMonths = ref([])
const request = axios.create({
  // 从环境变量中获取基础地址，自动适配开发/生产环境
  baseURL: import.meta.env.VITE_API_BASE_URL,
  // 可选：根据需要添加超时时间等配置
  // timeout: 5000
})

// 企业ID（可从登录信息中获取，这里先写死）
const companyId = ref(1)


// 公司信息
const company = ref({})

// 可选月份（假设固定）

const selectedMonth = ref(dayjs().format('YYYY-MM'))

// 多月账单数据
const bills = ref({
})

// 当前选中账单
const currentBill = computed(() => {
  const bill = bills.value[selectedMonth.value]

  return bill || {
    rent_due: 0,
    rent_paid: 0,
    property_fee: 0,
    utility_fee: 0,
    total_amount: 0,
    payment_status: 'unpaid'
  }
})

// // 缴费状态
// const isPaid = computed(() => currentBill.value.rent_paid >= currentBill.value.rent_due)
// 缴费状态 - 正确的实现
const isPaid = computed(() => {
  console.log('检查缴费状态:', {
    payment_status: currentBill.value.payment_status,
    rent_paid: currentBill.value.rent_paid,
    rent_due: currentBill.value.rent_due
  })
  
  // 使用支付状态字段判断
  return currentBill.value.payment_status === 'paid'
})


// 历史记录
const history = ref([

])

// 本月企业营收情况
const statistics = ref({

})

// 租金免租文本
const rentFreeText = computed(() => {
  const years = company.value.rentFreeYears
  const start = dayjs(company.value.rentFreeStart).format('YYYY年M月D日')
  return `免${years}年租金（${start}起）`
})

// 标签颜色
const tagType = computed(() =>
  company.value.type === '信息技术企业' ? 'success' :
  company.value.type === '劳动密集型企业' ? 'warning' : 'info'
)

// 货币格式化
const formatCurrency = (val) => {
  if (typeof val !== 'number') return '-'
  return '¥ ' + val.toLocaleString()
}

// 选择月份切换
const onMonthChange = () => {
  // 可加接口请求逻辑
  loadStatistics(selectedMonth.value)
}

// 缴费按钮点击
const payBill = async () => {
  try {
    await ElMessageBox.confirm(
      `确认缴纳 ${formatCurrency(currentBill.value.rent_due)} 的租金吗？`,
      '确认缴费',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 获取当前账单ID
    const billId = currentBill.value.id
    
    if (!billId) {
      ElMessage.error('无法获取账单ID')
      return
    }
    
    // 调用缴费API - 添加账单ID
    await request.post(`/api/company/pay`, {
      billId: billId, // 添加账单ID
      companyId: companyId.value,
      month: selectedMonth.value,
      amount: currentBill.value.rent_due
    })
    
    ElMessage.success('缴费成功')
    
    // 重新加载数据
    await loadBills()
    await loadHistory()
    await loadStatistics(selectedMonth.value)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('缴费失败: ' + (error.response?.data?.message || error.message))
      console.error(error)
    }
  }
}

// 加载企业信息

const loadCompanyInfo = async () => {
  try {
    const res = await request.get(`/api/company/info/${companyId.value}`)
    company.value = res.data.data // 直接使用API返回的数据结构
  } catch (e) {
    ElMessage.error('加载企业信息失败')
    console.error(e)
  }
}

// 加载账单数据

const loadBills = async () => {
  try {
    console.log('开始加载账单数据，当前月份:', selectedMonth.value)
    const res = await request.post('/api/company/query', {
      companyId: companyId.value,
      pageNumber: 1,
      pageSize: 100 // 获取足够多的记录
    })
    
  // 将records数组转换为月份键值对
  const billData = {}
  res.data.data.records.forEach(bill => {
    billData[bill.billMonth] = {
      id: bill.id,
      rent_due: bill.rentDue,
      rent_paid: bill.rentPaid,
      property_fee: bill.propertyFee,
      utility_fee: bill.utilityFee,
      total_amount: bill.totalAmount,
      payment_status: bill.paymentStatus
    }
  })
  bills.value = billData

        console.log('账单数据已更新:', bills.value)
      console.log('当前月份账单:', bills.value[selectedMonth.value])
    } catch (e) {
      ElMessage.error('加载账单失败')
      console.error(e)
    }
}

// 加载营收数据
const loadStatistics = async (month) => {
  try {
    const res = await request.get(`/api/company/statistics?companyId=${companyId.value}&month=${month}`)
    
    statistics.value = {
      revenue: res.data.data.revenue, // 总营收
      tax: res.data.data.tax, // 税收
      profit: res.data.data.profit // 利润
    }
  } catch (e) {
    ElMessage.error('加载营收数据失败')
    console.error(e)
  }
}

// 加载历史记录
const loadHistory = async () => {
  try {
    const res = await request.post('/api/company/history', {
      companyId: companyId.value,
      size: 100 // 获取100条记录
    })
    
    // 转换数据结构
    history.value = res.data.data.records.map(item => ({
      month: item.billMonth,
      rent_paid: item.paidAmount,
      property_fee: item.propertyFee,
      utility_fee: item.utilityFee,
      total: item.totalAmount
    }))
  } catch (e) {
    ElMessage.error('加载历史记录失败')
    console.error(e)
  }
}

// 修改availableMonths的获取方式
const loadAvailableMonths = async () => {
  try {
    const res = await request.get(`/api/company/months/${companyId.value}`)
    availableMonths.value = res.data.data
  } catch (e) {
    console.error('获取可用月份失败', e)
    // 可以设置一个默认值
    availableMonths.value = [dayjs().format('YYYY-MM')]
  }
}

// 在onMounted中添加调用
onMounted(async () => {
  await loadCompanyInfo()
  await loadAvailableMonths() // 先加载可用月份
  await loadBills()
  await loadStatistics(selectedMonth.value)
  await loadHistory()
})
</script>

<style scoped>
.company-bill-container {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.info-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}
.info-body p {
  margin: 0;
}
</style>